package com.shanghaionstar.user;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.more.entity.SubscriberDTO;
import com.onstar.cn.more.response.PrepaidCardResponse;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.ActivateType;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.notification.util.ShareUtils;
import com.shanghaionstar.user.iview.IUsePrepayCardView;
import com.shanghaionstar.user.presenter.UsePrepayCardPresenter;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.weight.TopLayout;

import java.util.Locale;

/**
 * Created by Mengzhou Gu on 2016/8/3.
 */
public class UsePrepayCardFragment extends BaseFragment implements View.OnFocusChangeListener,IUsePrepayCardView {
    private OnstarApplication myApp = null;
    @FindViewById
    private CircleImageView head_iv;
    private PrePayActivity parentActivitty  = null;
    @FindViewById
    private TopLayout             top_layout         = null;
    @FindViewById
    private TextView              tv_brand           = null;
    @FindViewById
    private TextView              tv_vin             = null;
    @FindViewById
    private TextView              tv_name            = null;
    @FindViewById
    private TextView              tv_phone_Value     = null;
    @FindViewById
    private DeleteEditText        et_carnumber_value = null;
    @FindViewById
    private DeleteEditText        et_password_value  = null;
    private ProgressDialog        dialog             = null;
    private Bundle                bundle             = null;
    // private ActivateCardResponse activateResponse = null;
    private String identity;// 身份标示
    private String       phonenumber      = null;// 游客电话号码
    @FindViewById
    private TextView     cardnumber_error = null;
    @FindViewById
    private TextView     password_error   = null;
    @FindViewById
    private LinearLayout layout_info      = null;
    // private GetAccountByVinResponse response = null;
    @FindViewById(background = R.drawable.onstar_join_me_bg)
    private RelativeLayout layout_background;

    @FindViewById(background = R.drawable.user_cardpay_head)
    private CustomImageView iv_icon;
    @FindViewById
    private Button          option_home_btn, activate_button;
    private SubscriberDTO       subscriberInfo;
    private String              vin;
    private  UsePrepayCardPresenter presenter;
    @Override
    public int getLayoutId() {
        return R.layout.user_usecard_fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        parentActivitty = (PrePayActivity) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        myApp = (OnstarApplication) getActivity().getApplicationContext();
        String imageUrl = ShareUtils.getString("imageUrl", parentActivitty);
        initView(imageUrl);

        bundle = getArguments();
       presenter = new UsePrepayCardPresenter(parentActivitty.getScheduler(), parentActivitty, et_carnumber_value, et_password_value, bundle);
        presenter.setView(this);
        if(bundle==null){
            return;
        }

        subscriberInfo = (SubscriberDTO) bundle.getSerializable("account_obj");
        vin = bundle.getString("vin");
        if (!ApplicationUtil.getInstance().isLogin()) {
            // 游客
            phonenumber = bundle.getString("phonenumber");
        }
        setUserInfo(vin);
        et_carnumber_value.setOnFocusChangeListener(this);
        et_password_value.setOnFocusChangeListener(this);
        top_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Activeforothers_activecancel.getStringValue());
                back();
            }
        });

    }

    private void initView(String url) {
        DisplayImageOptions options = OnstarApplication.getOptions(false, R.drawable.def_login_head);
        if (url!= null) {
            ImageLoader.getInstance().displayImage(url, head_iv, options);
        }
    }
   /* private void initView() {
        DisplayImageOptions options = OnstarApplication.getOptions(false, R.drawable.def_login_head);
        if (myApp.getHeadImgRes() != null) {
            ImageLoader.getInstance().displayImage(myApp.getHeadImgRes().getFullUrl(), head_iv, options);
        }
    }*/

    private void setUserInfo(String vin) {
        try {
            tv_brand.setText(subscriberInfo.getMake() + subscriberInfo.getModel());
            tv_vin.setText(CommonUtil.maskWithStar(vin,3,4));
            if (subscriberInfo.getLastName() != null && !subscriberInfo.getLastName().equals("")) {
                tv_name.setText(subscriberInfo.getLastName() + " " + getString(R.string.xx));
            }
            if (subscriberInfo.getPhoneNumber() != null && !subscriberInfo.getPhoneNumber().equals("")) {
                tv_phone_Value.setText(CommonUtil.replaceEmail(subscriberInfo.getPhoneNumber().toString(), false));
            } else {
                tv_phone_Value.setText(CommonUtil.replaceEmail(subscriberInfo.getEmail(), true));
            }
        } catch (Exception e) {

        }

    }

    @Override
    public void onResume() {
        super.onResume();
        parentActivitty.current_fragment = "UsePrepayCardfragment";

    }

//    public void changeFragment(FragmentManager fragmentManager, Fragment fragment, String tag) {
//        if (null != fragmentManager.findFragmentByTag(tag))
//            return;
//        FragmentTransaction p_FragmentTransaction = fragmentManager.beginTransaction();
//        p_FragmentTransaction.replace(R.id.fragment_container, fragment, tag);
//        p_FragmentTransaction.addToBackStack(null);
//        p_FragmentTransaction.commitAllowingStateLoss();
//    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_carnumber_value:
                if (!hasFocus) {
                    // 格式校验
                    if (!et_carnumber_value.getText().toString().trim().equals("")) {
                        if (et_carnumber_value.getText().length() != 10) {
                            cardnumber_error.setVisibility(View.VISIBLE);
                            cardnumber_error.setText(getString(R.string.SB027_MSG001));
                        }
                    } else {
                        cardnumber_error.setVisibility(View.VISIBLE);
                        cardnumber_error.setText(getString(R.string.SB027_MSG004));
                    }
                } else {
                    BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Activeforothers_inputcardNo.getStringValue());
                    cardnumber_error.setVisibility(View.GONE);
                }
                break;
            case R.id.et_password_value:
                if (!hasFocus) {
                    // 格式校验
                    if (!et_password_value.getText().toString().trim().equals("")) {

                    } else {
                        password_error.setVisibility(View.VISIBLE);
                        password_error.setText(getString(R.string.SB027_MSG004));
                    }
                } else {
                    BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Activeforothers_inputcardpw.getStringValue());
                    password_error.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
        DeleteEditText clearText = (DeleteEditText) v;
        clearText.hasFocus(hasFocus);
        if (hasFocus) {
            clearText.setDeleteIconVisible(clearText.getText().length() > 0);
        } else {
            clearText.setDeleteIconVisible(false);
        }

    }



    @OnClick({R.id.activate_button})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activate_button:
                BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Activeforothers_confirm.getStringValue());
                layout_info.setFocusable(true);
                layout_info.setFocusableInTouchMode(true);
                layout_info.requestFocus();

                CommonUtil.hideKeyBoard(getActivity(), et_password_value);
                if (CommonUtil.isNull(et_carnumber_value.getText().toString())
                        || CommonUtil.isNull(et_password_value.getText().toString())) {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setCode("SB027_MSG004");
                    ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo);
                    return;
                }
                if (et_carnumber_value.getText().length() != 10) {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setCode("SB027_MSG001");
                    ErrorCodeUtil.ShowErrorSompMsg(getActivity(), errorInfo);
                    return;
                }
                //activatePrepaidCard(subscriberInfo.getSubscriberID(), "1");
                presenter.getData(subscriberInfo.getSubscriberID(),"1");
                break;
            default:
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        top_layout = null;
    }

    @Override
    public void showSuccess(PrepaidCardResponse prepaidCardResponse) {
        try {
            Bundle bundles = new Bundle();
            if (prepaidCardResponse != null && prepaidCardResponse.getStatus().equals("VALID")) {
                bundles.putSerializable("obj", prepaidCardResponse);
                if (ApplicationUtil.getInstance().isLogin()) {
                    bundles.putString("phone", prepaidCardResponse.getAccountInfo().getPhoneNumber());
                } else {
                    bundles.putString("phone", phonenumber);
                }
                bundles.putString("card_number", et_carnumber_value.getText().toString().trim());
                bundles.putString("card_password", et_password_value.getText().toString().trim());
                bundles.putString("vin", bundle.getString("vin"));
                bundles.putSerializable("account_obj", subscriberInfo);
                bundles.putString("price", prepaidCardResponse.getPrice());
                PayCardDetailFragment activedetailfragment = new PayCardDetailFragment();
                bundles.putSerializable("activateType", ActivateType.Other);
                bundles.putString(FinalConstants.PREPAID_CARD_ACTIVATE_TYPE, ActivateType.Other.name().toUpperCase(Locale.CHINA));
                activedetailfragment.setArguments(bundles);
                parentActivitty.changeFragment(parentActivitty.fragmentManager, activedetailfragment,
                        PayCardDetailFragment.class,true);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void showFailure() {

    }

    @Override
    public void showError(Throwable throwable) {
        AlertDialogUtil.showDialogByExceptionCode(parentActivitty, (HttpException) throwable);
    }

    @Override
    public void setLoading(boolean isLoading) {
        if(isLoading){
            dialog=showLoadProgress();
            dialog.show();
        }else {
            dismissDialog(dialog);
        }
    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(PrepaidCardResponse object) {

    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void onFragmentBackPress() {
//        back();
        parentActivitty.getSupportFragmentManager().popBackStack();

        BusinessUtil.sendReportByClickType(getActivity(),FunctionNameFindId.Activeforothers_activecancel.getStringValue());

    }
}
